<template>
  <div>
    <el-button v-if="isAdding" @click="addToCart" type="success" size="small">
      加入购物车
    </el-button>
    <el-button v-else @click="removeFromCart(product._id, product.price)" type="danger" size="small">
      从购物车移除
    </el-button>
  </div>
</template>

<script>
import { Message } from 'element-ui';
export default {
  props: ["id"],
  computed: {
    product() {
      let product = this.$store.getters.allProducts.find(product => product._id === this.id)
      return product;
    },
    isAdding() {
      let isAdding = true;
      this.cart.map((product) => {
        if (product._id === this.product._id) {
          isAdding = false;
        }
      });
      return isAdding;
    },
    cart() {
      return this.$store.state.cart;
    },
  },
  methods: {
    isLogged() {
      return !!this.$store.state.user.token;
    },
    addToCart() {
      if (!this.isLogged()) {
        Message({
          message: '请先登录',
          type: 'info',
        });
        this.$router.push("/user/login");
        return;
      }
      this.$store.commit('ADD_TO_CART', {
        product: this.product,
      })
    },
    removeFromCart(productId, price) {
      if (!this.isLogged()) {
        this.$router.push("/user/login");
        return;
      }
      this.$store.commit('REMOVE_FROM_CART', {
        productId,
        price
      })
    }
  }
};
</script>